package com.yidu.qianfeng.controller;

import com.yidu.qianfeng.common.bean.company.EmpInfo;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContext;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

/**
 * @Author: 刘宇轩
 * @Description: 员工视图层
 * @Date Created in 16:31 2021/3/17
 * @since 1.0
 */

@Controller("userController")
public class UserController {

    /**
     * 获取当前登录的员工
     * @param request 请求对象
     * @return 当前登录员工实体
     */
    @RequestMapping("/getLoginedEmp")
    public @ResponseBody
    EmpInfo getLoginedUser(HttpServletRequest request) {

        return UserController.getLoginEmpInfo(request);
    }

    /**
     * 获取登录的员工对象
     * @param request 请求对象
     * @return 登录后的员工信息
     */
    public static EmpInfo getLoginEmpInfo(HttpServletRequest request){
        //获得session对象
        HttpSession session = request.getSession();

        //获取session对象中的SPRING_SECURITY_CONTEXT属性保存为Object
        Object spring_security_context = session.getAttribute("SPRING_SECURITY_CONTEXT");
        //转型为SecurityContext对象
        SecurityContext securityContext = (SecurityContext) spring_security_context;
        //获得认证信息，Authentication类
        Authentication authentication = securityContext.getAuthentication();
        //获得用户详情，getPrincipal获取当前认证用户
        Object principal = authentication.getPrincipal();
        //转换为员工对象
        EmpInfo emp = (EmpInfo) principal;
        //新生成员工对象作为副本
        EmpInfo empInfo = new EmpInfo();

        //获取员工对象并赋值到员工对象副本中
        //设置员工账号
        empInfo.setEmpAccount(emp.getEmpAccount());
        //设置员工姓名
        empInfo.setEmpName(emp.getEmpName());
        //设置员工部门
        empInfo.setEmpDepartment(emp.getEmpDepartment());
        //设置员工所在分站id
        empInfo.setEmpSubstId(emp.getEmpSubstId());
        //设置员工权限列表
        empInfo.setAuthorities(emp.getAuthorities());

        return empInfo;

    }




}
